# cron: 30 22 * * *
# new Env("甬派运行记录统计")
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
青龙面板日志分析脚本（增强版）
功能：精确统计抽奖结果，支持动态目录和推送通知
"""

import os
import glob
import re
import requests
from collections import defaultdict
import logging
from datetime import datetime

# ============== 配置区域 ==============
LOG_DIR_PATTERN = "/ql/data/log/XinWen_甬音_Loader_*"  # 动态匹配版本号变化的目录
REPORT_FILE = "/ql/data/log/Message/PUSH_yp.log"  # 新增：报告保存路径
# ====================================

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("YongPaiStats")

def get_latest_log_dir():
    """获取最新版本的日志目录"""
    return max(glob.glob(LOG_DIR_PATTERN), key=os.path.getmtime) if glob.glob(LOG_DIR_PATTERN) else None

def get_latest_log_file(log_dir):
    """获取目录下最新的日志文件"""
    log_files = glob.glob(os.path.join(log_dir, "*.log")) or glob.glob(os.path.join(log_dir, "*"))
    return max(log_files, key=os.path.getmtime) if log_files else None

def analyze_log(log_content):
    """精准日志分析"""
    account_stats = defaultdict(lambda: {
        'rewards': [],
        'current_total': 0.0,
        'history_total': 0.0,
        'success': False
    })
    
    current_account = None
    patterns = {
        'account': re.compile(r'--------开始第(\d+)个账号--------'),
        'success': re.compile(r'抽奖成功,奖品\[现金([0-9.]+)元\]'),
        'fail': re.compile(r'抽奖失败\[.*\]'),
        'total': re.compile(r'总获\[([0-9.]+)\]')
    }
    
    for line in log_content.split('\n'):
        if m := patterns['account'].search(line):
            current_account = f"账号{m.group(1)}"
            account_stats[current_account].update(rewards=[], current_total=0.0, history_total=0.0, success=False)
        
        if current_account:
            if m := patterns['success'].search(line):
                amount = float(m.group(1))
                if len(account_stats[current_account]['rewards']) < 4:
                    account_stats[current_account]['rewards'].append(amount)
                    account_stats[current_account]['current_total'] += amount
            elif patterns['fail'].search(line):
                if len(account_stats[current_account]['rewards']) < 4:
                    account_stats[current_account]['rewards'].append('失败')
            elif m := patterns['total'].search(line):
                account_stats[current_account]['history_total'] = float(m.group(1))
    
    for acc in account_stats.values():
        acc['success'] = any(isinstance(r, float) for r in acc['rewards'])
        # 确保每个账号都有4次抽奖记录
        acc['rewards'] = acc['rewards'][:4] + ['失败']*(4-len(acc['rewards']))
    
    return account_stats

def generate_report(stats):
    """生成可视化报告"""
    total_current = sum(acc['current_total'] for acc in stats.values())
    total_history = sum(acc['history_total'] for acc in stats.values())
    success_count = sum(1 for acc in stats.values() if acc['success'])
    fail_count = len(stats) - success_count
    
    report = [
        "📊 甬派运行记录统计报告",
        "="*40,
        f"📅 报告时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
        "-"*40,
        f"• 总账号数: {len(stats)}",
        f"• 成功账号: {success_count}",
        f"• 失败账号: {fail_count}",
        f"• 本次总获: {total_current:.2f}元",
        f"• 历史累计: {total_history:.2f}元",
        f"• 成功率: {success_count/len(stats):.0%}",
        "-"*40,
        "📝 账号详情:"
    ]
    
    for acc in sorted(stats.keys(), key=lambda x: int(x[2:])):
        data = stats[acc]
        status = "✅" if data['success'] else "❌"
        rewards = [f"{r:.2f}元" if isinstance(r, float) else r for r in data['rewards']]
        
        line = f"{status} {acc}: " + " + ".join(rewards)
        line += f" = {data['current_total']:.2f}元 ｜ 总获: {data['history_total']:.2f}元"
        report.append(line)
    
    if failed := [k for k,v in stats.items() if not v['success']]:
        report.extend(["\n⚠️ 全败账号:", *[f"• {acc}" for acc in failed]])
    
    report.append("="*40)
    report.append("Generated by YongPaiStats")
    
    return "\n".join(report)

def save_report_to_file(report_content):
    """保存报告到文件"""
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(REPORT_FILE), exist_ok=True)
        
        with open(REPORT_FILE, 'w', encoding='utf-8') as f:
            f.write(report_content)
        logger.info(f"报告已保存至: {REPORT_FILE}")
        return True
    except Exception as e:
        logger.error(f"保存报告失败: {str(e)}")
        return False

def pushplus_notify(content):
    """发送推送通知"""
    if not (token := os.getenv('PUSH_PLUS_TOKEN')):
        logger.warning("未配置PUSH_PLUS_TOKEN，跳过推送")
        return "未配置PUSH_PLUS_TOKEN"
    
    url = "http://www.pushplus.plus/send"
    params = {
        "token": token,
        "user": os.getenv('PUSH_PLUS_USER'),
        "title": "甬派运行记录统计报告",
        "content": content,
        "template": "txt"
    }
    try:
        response = requests.post(url, json=params)
        result = response.json()
        if response.status_code == 200 and result.get('code') == 200:
            logger.info("推送成功")
            return "推送成功"
        else:
            logger.error(f"推送失败: {result.get('msg', '未知错误')}")
            return f"推送失败: {result.get('msg', '未知错误')}"
    except Exception as e:
        logger.error(f"推送失败: {str(e)}")
        return f"推送失败: {str(e)}"

def main():
    logger.info("====== 甬派日志分析开始 ======")
    
    if not (log_dir := get_latest_log_dir()):
        logger.error("错误：未找到日志目录")
        return
    
    logger.info(f"使用日志目录: {log_dir}")
    
    if not (log_file := get_latest_log_file(log_dir)):
        logger.error(f"目录 {log_dir} 中没有日志文件")
        return
    
    logger.info(f"分析日志文件: {log_file}")
    
    try:
        with open(log_file, 'r', encoding='utf-8') as f:
            content = f.read()
            stats = analyze_log(content)
            report = generate_report(stats)
            
            # 打印报告到日志
            logger.info("\n" + report)
            
            # 保存报告到文件
            save_report_to_file(report)
            
            # 推送报告
            push_result = pushplus_notify(report)
            logger.info(f"推送结果: {push_result}")
    except Exception as e:
        logger.error(f"处理失败: {str(e)}")
    
    logger.info("====== 分析完成 ======")

if __name__ == '__main__':
    main()